package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1.参数校验
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数异常!");
        }
        //2.判断用户是否存在
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName());
        int count = this.count(wrapper);
        if(count==0){
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"该用户不存在!");
        }
        AdUser adUser = this.getOne(wrapper);
       //3.校验密码是否一致
        String iuputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        if(!iuputPwd.equals(adUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误!");
        }
        //3.1检验用户状态是否正常
        if(adUser.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常!");
        }
        //3.2修改登陆时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //4.生成token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //5.封装返回数据
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,userVO);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",userVO);
        return ResponseResult.okResult(map);
    }
}
